import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:gt_flutter_admin/app/routes.dart';
import 'package:gt_flutter_admin/models/index.dart';
import 'package:gt_flutter_admin/services/api_service.dart';
import 'package:gt_flutter_admin/utils/storage_utils.dart';
import 'package:gt_flutter_admin/utils/toast_utils.dart';

class LoginController extends GetxController with StateMixin<Captcha> {
  // 数据
  final Rx<Captcha> captcha = Captcha().obs;

  // 文本控件
  final TextEditingController nameText = TextEditingController();
  final TextEditingController passwordText = TextEditingController();
  final TextEditingController codeText = TextEditingController();

  @override
  void onInit() {
    super.onInit();

    onChangeCaptcha();
  }

  /// 更新图形验证码
  void onChangeCaptcha() async {
    change(null, status: RxStatus.loading());
    this.captcha.value = await getCaptcha();
    change(this.captcha.value, status: RxStatus.success());
  }

  /// 提交登录表单
  void onSubmit() async {
    Token token = await login({
      'key': this.captcha.value.key,
      'mobile': nameText.text,
      'password': passwordText.text,
      'verifyCode': codeText.text,
    });
    StorageUtils.writeToken(token.token!);

    // 获取当前用户信息
    User user = await getCurrentUser();
    StorageUtils.writeUser(user);

    ToastUtils.success('登录成功');
    Get.rootDelegate.offNamed(Routes.USER);
  }
}
